const nodemailer = require('nodemailer');
const { config } = require('../config');

class EmailChannel {
  constructor(customConfig) {
    this.cfg = customConfig || config.email;
    if (!this.cfg.host || !this.cfg.user || !this.cfg.pass || !this.cfg.from) {
      throw new Error('SMTP settings (host,user,pass,from) are required');
    }
    this.transporter = nodemailer.createTransport({
      host: this.cfg.host,
      port: this.cfg.port,
      secure: this.cfg.secure,
      auth: { user: this.cfg.user, pass: this.cfg.pass }
    });
  }

  async send(message) {
    const to = Array.isArray(message.to) ? message.to.join(',') : message.to;
    if (!to) {
      throw new Error('Email "to" is required');
    }
    const mail = {
      from: this.cfg.from,
      to,
      subject: message.subject || message.title || 'Notification',
      text: message.text || message.body || '',
      html: message.html
    };
    const info = await this.transporter.sendMail(mail);
    return { ok: true, messageId: info.messageId, accepted: info.accepted, rejected: info.rejected };
  }
}

module.exports = { EmailChannel };


